import 'package:flutter/material.dart';
import '../models/conversation.dart';
import '../models/chat_message.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:io';
import '../widgets/image_preview.dart';

/// 面板类型枚举
enum PanelType {
  none,
  emoji,
  action,
}

class ChatPage extends StatefulWidget {
  final Conversation conversation;

  const ChatPage({
    super.key,
    required this.conversation,
  });

  @override
  State<ChatPage> createState() => _ChatPageState();
}

class _ChatPageState extends State<ChatPage> with SingleTickerProviderStateMixin {
  final _messageController = TextEditingController();
  final _scrollController = ScrollController();
  bool _showEmojiPanel = false;
  bool _showActionPanel = false;
  bool _hasContent = false;  // 添加状态变量
  
  // 修改动画控制器和动画的声明方式
  late final AnimationController _panelController = AnimationController(
    duration: const Duration(milliseconds: 300),
    vsync: this,
  );

  late final Animation<double> _panelAnimation = CurvedAnimation(
    parent: _panelController,
    curve: Curves.easeOutCubic,
    reverseCurve: Curves.easeInCubic,
  );

  // 添加面板高度常量
  static const double _emojiPanelHeight = 200.0;
  static const double _actionPanelHeight = 120.0;

  // 修改状态变量
  PanelType _currentPanel = PanelType.none;

  // 修改消息列表的初始化数据
  final List<ChatMessage> _messages = [
    ChatMessage(
      id: '1',
      content: '您好，请问什么时候可以上门搬家？',
      time: '14:30',
      isSender: false,
      avatar: 'https://api.dicebear.com/7.x/avataaars/png?seed=Felix',  // 添加头像
    ),
    ChatMessage(
      id: '2',
      content: '师傅您好，我这边预约的是明天上午9点',
      time: '14:31',
      isSender: true,
      avatar: 'https://api.dicebear.com/7.x/avataaars/png?seed=John',
    ),
    ChatMessage(
      id: '3',
      content: '好的，请问地址是哪里？',
      time: '14:32',
      isSender: false,
      avatar: 'https://api.dicebear.com/7.x/avataaars/png?seed=Felix',
    ),
    ChatMessage(
      id: '4',
      content: '北京市朝阳区望京SOHO',
      time: '14:33',
      isSender: true,
      avatar: 'https://api.dicebear.com/7.x/avataaars/png?seed=John',
    ),
    ChatMessage(
      id: '5',
      type: ChatMessageType.image,
      content: '[图片]',
      time: '14:34',
      isSender: true,
      avatar: 'https://api.dicebear.com/7.x/avataaars/png?seed=John',
      imageUrl: 'https://picsum.photos/800/600?random=1',
    ),
    ChatMessage(
      id: '6',
      content: '这是我们的搬家物品清单',
      time: '14:34',
      isSender: true,
      avatar: 'https://api.dicebear.com/7.x/avataaars/png?seed=John',
    ),
    ChatMessage(
      id: '7',
      content: '好的，我看到了。请问有大件家具吗？',
      time: '14:35',
      isSender: false,
      avatar: 'https://api.dicebear.com/7.x/avataaars/png?seed=Felix',
    ),
  ];

  // 移除 _actionItems 的初始化
  late final List<Map<String, dynamic>> _actionItems;

  @override
  void initState() {
    super.initState();
    // 在 initState 中初始化 _actionItems
    _actionItems = [
      {
        'icon': Icons.image_outlined,
        'label': '图片',
        'onTap': _pickAndSendImage,
      },
      {
        'icon': Icons.camera_alt_outlined,
        'label': '拍照',
        'onTap': () {
          // TODO: 实现拍照功能
        },
      },
      {
        'icon': Icons.location_on_outlined,
        'label': '位置',
        'onTap': _sendLocation,
      },
    ];
    // 添加输入框监听
    _messageController.addListener(() {
      final hasContent = _messageController.text.trim().isNotEmpty;
      if (hasContent != _hasContent) {
        setState(() {
          _hasContent = hasContent;
        });
      }
    });
  }

  /// 构建操作面板
  Widget _buildActionPanel() {
    return Container(
      height: 120,
      padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 16),
      child: LayoutBuilder(
        builder: (context, constraints) {
          final itemWidth = 76.0;
          final maxItems = (constraints.maxWidth / itemWidth).floor();
          final totalWidth = itemWidth * _actionItems.length;
          
          return SingleChildScrollView(
            scrollDirection: Axis.horizontal,
            child: Container(
              width: totalWidth > constraints.maxWidth ? totalWidth : constraints.maxWidth,
              child: Row(
                mainAxisAlignment: totalWidth > constraints.maxWidth 
                    ? MainAxisAlignment.start 
                    : MainAxisAlignment.spaceEvenly,
                children: _actionItems.map((item) => 
                  GestureDetector(
                    onTap: () => item['onTap'](),  // 修改调用方式
                    child: SizedBox(
                      width: itemWidth,
                      child: Column(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Container(
                            width: 52,
                            height: 52,
                            decoration: BoxDecoration(
                              color: Colors.white,
                              borderRadius: BorderRadius.circular(12),
                              border: Border.all(
                                color: const Color(0xFFEEEEEE),
                              ),
                            ),
                            child: Icon(
                              item['icon'],
                              color: Colors.grey[600],
                              size: 26,
                            ),
                          ),
                          const SizedBox(height: 8),
                          Text(
                            item['label'],
                            style: TextStyle(
                              fontSize: 12,
                              color: Colors.grey[600],
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                ).toList(),
              ),
            ),
          );
        },
      ),
    );
  }

  /// 构建表情面板
  Widget _buildEmojiPanel() {
    final List<String> emojis = [
      '😀', '😃', '😄', '😁', '😅', '😂', '🤣', '😊',
      '😇', '🙂', '🙃', '😉', '😌', '😍', '🥰', '😘',
      '😗', '😙', '😚', '😋', '😛', '😝', '😜', '🤪',
      '🤨', '🧐', '🤓', '😎', '🤩', '🥳', '😏', '😒',
      '😞', '😔', '😟', '😕', '🙁', '☹️', '😣', '😖',
    ];

    return Container(
      height: 200,
      padding: const EdgeInsets.all(16),
      child: GridView.builder(
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 8,
          mainAxisSpacing: 12,
          crossAxisSpacing: 12,
        ),
        itemCount: emojis.length,
        itemBuilder: (context, index) {
          return GestureDetector(
            onTap: () {
              final text = _messageController.text;
              final selection = _messageController.selection;
              final emoji = emojis[index];

              // 处理无效的选择范围
              final start = selection.isValid ? selection.start : text.length;
              final end = selection.isValid ? selection.end : text.length;

              // 在光标位置或文本末尾插入表情
              final newText = text.replaceRange(start, end, emoji);
              
              _messageController.value = TextEditingValue(
                text: newText,
                selection: TextSelection.collapsed(
                  offset: start + emoji.length,
                ),
              );

              // 确保输入框获得焦点
              FocusScope.of(context).requestFocus();
            },
            child: Container(
              decoration: BoxDecoration(
                color: Colors.grey[100],
                borderRadius: BorderRadius.circular(4),
              ),
              child: Center(
                child: Text(
                  emojis[index],
                  style: const TextStyle(
                    fontSize: 24,
                  ),
                ),
              ),
            ),
          );
        },
      ),
    );
  }

  @override
  void dispose() {
    _messageController.dispose();
    _scrollController.dispose();
    _panelController.dispose();
    super.dispose();
  }

  /// 切换面板显示状态
  void _togglePanel(bool showEmoji) async {
    final newPanel = showEmoji 
        ? (_currentPanel == PanelType.emoji ? PanelType.none : PanelType.emoji)
        : (_currentPanel == PanelType.action ? PanelType.none : PanelType.action);

    if (newPanel == PanelType.none) {
      await _panelController.reverse();
      if (mounted) {
        setState(() {
          _currentPanel = newPanel;
        });
      }
    } else {
      setState(() {
        _currentPanel = newPanel;
        FocusScope.of(context).unfocus();
      });
      _panelController.forward();
    }
  }

  /// 隐藏所有面板
  void _hideAllPanels() async {
    if (_currentPanel != PanelType.none) {
      await _panelController.reverse();
      if (mounted) {
        setState(() {
          _currentPanel = PanelType.none;
        });
      }
    }
  }

  /// 构建面板内容
  Widget _buildPanelContent() {
    switch (_currentPanel) {
      case PanelType.emoji:
        return SizedBox(
          height: _emojiPanelHeight,
          child: _buildEmojiPanel(),
        );
      case PanelType.action:
        return SizedBox(
          height: _actionPanelHeight,
          child: _buildActionPanel(),
        );
      case PanelType.none:
        return const SizedBox.shrink();
    }
  }

  /// 发送消息
  Future<void> _sendMessage(String content, {ChatMessageType type = ChatMessageType.text}) async {
    if (content.trim().isEmpty) return;

    final message = ChatMessage(
      id: DateTime.now().toString(),
      content: content,
      time: DateTime.now().toString().substring(11, 16),
      isSender: true,
      type: type,
      status: MessageStatus.sending,
    );

    setState(() {
      _messages.add(message);
      _messageController.clear();
    });

    // 滚动到底部
    await Future.delayed(const Duration(milliseconds: 100));
    _scrollController.animateTo(
      _scrollController.position.maxScrollExtent,
      duration: const Duration(milliseconds: 300),
      curve: Curves.easeOut,
    );

    // 模拟发送延迟
    await Future.delayed(const Duration(seconds: 1));
    
    if (mounted) {
      setState(() {
        final index = _messages.indexWhere((m) => m.id == message.id);
        if (index != -1) {
          _messages[index] = ChatMessage(
            id: message.id,
            content: message.content,
            time: message.time,
            isSender: true,
            type: message.type,
            status: MessageStatus.sent,
            imageUrl: message.imageUrl,
            location: message.location,
          );
        }
      });
    }
  }

  /// 选择并发送图片
  Future<void> _pickAndSendImage() async {
    try {
      print('开始选择图片...');
      
      // 简化图片选择逻辑
      final image = await ImagePicker().pickImage(
        source: ImageSource.gallery,
      );

      print('图片选择结果: ${image?.path}');
      if (image == null) {
        print('未选择图片');
        return;
      }

      // 隐藏操作面板
      _hideAllPanels();

      print('创建消息...');
      // 创建消息
      final message = ChatMessage(
        id: DateTime.now().toString(),
        content: '[图片]',
        time: DateTime.now().toString().substring(11, 16),
        isSender: true,
        type: ChatMessageType.image,
        status: MessageStatus.sending,
        imageUrl: image.path,
      );

      print('添加消息到列表...');
      setState(() {
        _messages.add(message);
      });

      // 滚动到底部
      await Future.delayed(const Duration(milliseconds: 100));
      if (_scrollController.hasClients) {
        _scrollController.animateTo(
          _scrollController.position.maxScrollExtent,
          duration: const Duration(milliseconds: 300),
          curve: Curves.easeOut,
        );
      }

      // 模拟上传延迟
      await Future.delayed(const Duration(seconds: 1));

      print('更新消息状态...');
      if (mounted) {
        setState(() {
          final index = _messages.indexWhere((m) => m.id == message.id);
          if (index != -1) {
            _messages[index] = message.copyWith(
              status: MessageStatus.sent,
            );
          }
        });
      }
    } catch (e, stackTrace) {
      print('图片发送失败');
      print('错误: $e');
      print('堆栈: $stackTrace');
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('图片选择失败，请重试'),
            behavior: SnackBarBehavior.floating,
          ),
        );
      }
    }
  }

  /// 发送位置信息
  Future<void> _sendLocation() async {
    // TODO: 实现位置选择和发送
    final message = ChatMessage(
      id: DateTime.now().toString(),
      content: '[位置]',
      time: DateTime.now().toString().substring(11, 16),
      isSender: true,
      type: ChatMessageType.location,
      status: MessageStatus.sending,
      location: {
        'latitude': 39.9042,
        'longitude': 116.4074,
        'address': '北京市东城区天安门',
      },
    );

    setState(() {
      _messages.add(message);
    });

    // 滚动到底部和状态更新逻辑...
  }

  /// 修改头像显示部分
  Widget _buildAvatar(String? avatar, bool isSender) {
    return CircleAvatar(
      radius: 20,
      backgroundColor: Colors.grey[200],
      backgroundImage: avatar != null ? NetworkImage(avatar) : null,
      child: avatar == null
          ? Icon(
              Icons.person_outline,
              color: Colors.grey[400],
            )
          : null,
    );
  }

  /// 修改消息气泡
  Widget _buildMessageBubble(ChatMessage message) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 8),
      child: Row(
        mainAxisAlignment: message.isSender ? MainAxisAlignment.end : MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          if (!message.isSender) ...[
            Padding(
              padding: const EdgeInsets.only(left: 16),
              child: _buildAvatar(message.avatar, message.isSender),
            ),
            const SizedBox(width: 8),
          ],

          ConstrainedBox(
            constraints: BoxConstraints(
              maxWidth: MediaQuery.of(context).size.width * 0.65,
            ),
            child: Column(
              crossAxisAlignment: message.isSender ? CrossAxisAlignment.end : CrossAxisAlignment.start,
              children: [
                // 根据消息类型决定是否使用气泡容器
                if (message.type == ChatMessageType.text)
                  Container(
                    margin: const EdgeInsets.only(bottom: 4),
                    padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
                    decoration: BoxDecoration(
                      color: message.isSender ? const Color(0xFFFF5722) : Colors.white,
                      borderRadius: BorderRadius.circular(16).copyWith(
                        bottomRight: message.isSender ? const Radius.circular(4) : null,
                        bottomLeft: !message.isSender ? const Radius.circular(4) : null,
                      ),
                      boxShadow: [
                        BoxShadow(
                          color: Colors.black.withOpacity(0.05),
                          blurRadius: 4,
                          offset: const Offset(0, 2),
                        ),
                      ],
                    ),
                    child: _buildMessageContent(message),
                  )
                else
                  Padding(
                    padding: const EdgeInsets.only(bottom: 4),
                    child: _buildMessageContent(message),
                  ),
                
                // 时间和状态指示
                Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Text(
                      message.time,
                      style: TextStyle(
                        fontSize: 12,
                        color: Colors.grey[500],
                      ),
                    ),
                    if (message.isSender) ...[
                      const SizedBox(width: 4),
                      _buildMessageStatus(message.status),
                    ],
                  ],
                ),
              ],
            ),
          ),

          if (message.isSender) ...[
            const SizedBox(width: 8),
            Padding(
              padding: const EdgeInsets.only(right: 16),
              child: _buildAvatar(message.avatar, message.isSender),
            ),
          ],
        ],
      ),
    );
  }

  /// 构建消息气泡内容
  Widget _buildMessageContent(ChatMessage message) {
    switch (message.type) {
      case ChatMessageType.text:
        return Text(
          message.content,
          style: TextStyle(
            fontSize: 15,
            color: message.isSender ? Colors.white : Colors.black87,
            height: 1.4,
          ),
        );
      
      case ChatMessageType.image:
        return GestureDetector(
          onTap: () {
            // 获取所有图片消息的URL列表
            final imageUrls = _messages
                .where((m) => m.type == ChatMessageType.image)
                .map((m) => m.imageUrl!)
                .toList();
            
            // 获取当前图片在列表中的索引
            final currentIndex = imageUrls.indexOf(message.imageUrl!);
            
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => ImagePreview(
                  imageUrls: imageUrls,
                  initialIndex: currentIndex,
                ),
              ),
            );
          },
          child: Hero(
            tag: message.imageUrl!,
            child: Container(
              constraints: BoxConstraints(
                maxWidth: MediaQuery.of(context).size.width * 0.6,
                maxHeight: 200,
              ),
              child: ClipRRect(
                borderRadius: BorderRadius.circular(8),
                child: message.imageUrl!.startsWith('http')
                    ? Image.network(
                        message.imageUrl!,
                        fit: BoxFit.cover,
                        loadingBuilder: (context, child, loadingProgress) {
                          if (loadingProgress == null) return child;
                          return _buildImageLoadingPlaceholder(loadingProgress);
                        },
                        errorBuilder: (context, error, stackTrace) => 
                            _buildImageErrorPlaceholder(),
                      )
                    : Image.file(
                        File(message.imageUrl!),
                        fit: BoxFit.cover,
                        errorBuilder: (context, error, stackTrace) => 
                            _buildImageErrorPlaceholder(),
                      ),
              ),
            ),
          ),
        );
      
      case ChatMessageType.location:
        return Container(
          width: 200,
          height: 100,
          decoration: BoxDecoration(
            color: Colors.grey[200],
            borderRadius: BorderRadius.circular(8),
          ),
          child: Stack(
            children: [
              // TODO: 添加地图预览
              Center(
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    const Icon(
                      Icons.location_on,
                      color: Colors.grey,
                    ),
                    const SizedBox(height: 4),
                    Text(
                      message.location?['address'] ?? '未知位置',
                      style: const TextStyle(
                        fontSize: 12,
                        color: Colors.grey,
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        );
    }
  }

  Widget _buildImageLoadingPlaceholder(ImageChunkEvent loadingProgress) {
    return Container(
      width: 200,
      height: 150,
      color: Colors.grey[200],
      child: Center(
        child: CircularProgressIndicator(
          value: loadingProgress.expectedTotalBytes != null
              ? loadingProgress.cumulativeBytesLoaded / 
                  loadingProgress.expectedTotalBytes!
              : null,
          strokeWidth: 2,
          valueColor: const AlwaysStoppedAnimation<Color>(Color(0xFFFF5722)),
        ),
      ),
    );
  }

  Widget _buildImageErrorPlaceholder() {
    return Container(
      width: 200,
      height: 150,
      color: Colors.grey[200],
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.broken_image_outlined,
            color: Colors.grey[400],
            size: 32,
          ),
          const SizedBox(height: 4),
          Text(
            '图片加载失败',
            style: TextStyle(
              fontSize: 12,
              color: Colors.grey[400],
            ),
          ),
        ],
      ),
    );
  }

  /// 构建消息状态指示图标
  Widget _buildMessageStatus(MessageStatus status) {
    IconData icon;
    Color color;

    switch (status) {
      case MessageStatus.sending:
        icon = Icons.access_time;
        color = Colors.grey[400]!;
      case MessageStatus.sent:
        icon = Icons.done;
        color = Colors.grey[400]!;
      case MessageStatus.read:
        icon = Icons.done_all;
        color = Colors.grey[400]!;
      case MessageStatus.failed:
        icon = Icons.error_outline;
        color = Colors.red;
    }

    return Icon(
      icon,
      size: 14,
      color: color,
    );
  }

  @override
  Widget build(BuildContext context) {
    final keyboardHeight = MediaQuery.of(context).viewInsets.bottom;
    
    return GestureDetector(
      onTap: () {
        // 点击空白区域时，同时处理输入框失焦和面板隐藏
        FocusScope.of(context).unfocus();
        _hideAllPanels();
      },
      child: Scaffold(
        backgroundColor: const Color(0xFFF5F5F5),
        appBar: AppBar(
          title: Column(
            children: [
              Text(
                widget.conversation.customerName,
                style: const TextStyle(
                  fontSize: 17,
                  fontWeight: FontWeight.w500,
                ),
              ),
              Text(
                '订单号：${widget.conversation.orderId}',
                style: TextStyle(
                  fontSize: 12,
                  color: Colors.grey[400],
                ),
              ),
            ],
          ),
          centerTitle: true,
          backgroundColor: Colors.white,
          elevation: 0,
        ),
        body: Column(
          children: [
            Expanded(
              child: GestureDetector(
                onTap: () {
                  // 点击消息列表区域时，同时处理输入框失焦和面板隐藏
                  FocusScope.of(context).unfocus();
                  _hideAllPanels();
                },
                child: ListView.builder(
                  controller: _scrollController,
                  padding: EdgeInsets.zero,
                  itemCount: _messages.length,
                  itemBuilder: (context, index) => _buildMessageBubble(_messages[index]),
                ),
              ),
            ),
            Container(
              decoration: BoxDecoration(
                color: Colors.white,
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withOpacity(0.05),
                    blurRadius: 8,
                    offset: const Offset(0, -1),
                  ),
                ],
              ),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Padding(
                    padding: EdgeInsets.only(
                      left: 8,
                      right: 8,
                      top: 8,
                      bottom: 8 + (keyboardHeight > 0 ? 0 : MediaQuery.of(context).padding.bottom),
                    ),
                    child: Row(
                      children: [
                        IconButton(
                          onPressed: () => _togglePanel(true),
                          icon: Icon(
                            _currentPanel == PanelType.emoji
                                ? Icons.keyboard_alt_outlined
                                : Icons.emoji_emotions_outlined,
                            color: _currentPanel == PanelType.emoji
                                ? const Color(0xFFFF5722)
                                : Colors.grey[600],
                            size: 24,
                          ),
                          padding: const EdgeInsets.all(8),
                          constraints: const BoxConstraints(),
                          visualDensity: VisualDensity.compact,
                        ),
                        const SizedBox(width: 4),
                        Expanded(
                          child: TextField(
                            controller: _messageController,
                            decoration: InputDecoration(
                              hintText: '输入消息...',
                              hintStyle: TextStyle(
                                color: Colors.grey[400],
                              ),
                              contentPadding: const EdgeInsets.symmetric(
                                horizontal: 12,
                                vertical: 8,
                              ),
                              filled: true,
                              fillColor: const Color(0xFFF5F5F5),
                              border: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(8),
                                borderSide: BorderSide.none,
                              ),
                              enabledBorder: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(8),
                                borderSide: BorderSide(
                                  color: Colors.grey[200]!,
                                  width: 1,
                                ),
                              ),
                              focusedBorder: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(8),
                                borderSide: const BorderSide(
                                  color: Color(0xFFFF5722),
                                  width: 1,
                                ),
                              ),
                            ),
                            maxLines: 4,
                            minLines: 1,
                            onTap: _hideAllPanels,
                            onTapOutside: (event) {
                              // 点击输入框外部时，如果表情面板打开则不失焦
                              if (_currentPanel != PanelType.emoji) {
                                FocusScope.of(context).unfocus();
                              }
                            },
                          ),
                        ),
                        const SizedBox(width: 4),
                        IconButton(
                          onPressed: () => _togglePanel(false),
                          icon: Icon(
                            Icons.add_circle_outline,
                            color: _currentPanel == PanelType.action
                                ? const Color(0xFFFF5722)
                                : Colors.grey[600],
                            size: 24,
                          ),
                          padding: const EdgeInsets.all(8),
                          constraints: const BoxConstraints(),
                          visualDensity: VisualDensity.compact,
                        ),
                        const SizedBox(width: 4),
                        IconButton(
                          onPressed: _hasContent  // 根据是否有内容决定是否可点击
                              ? () {
                                  final content = _messageController.text.trim();
                                  if (content.isNotEmpty) {
                                    _sendMessage(content);
                                  }
                                }
                              : null,
                          icon: const Icon(
                            Icons.send,
                            size: 24,
                          ),
                          color: _hasContent  // 根据是否有内容决定颜色
                              ? const Color(0xFFFF5722)
                              : Colors.grey[400],
                          padding: const EdgeInsets.all(8),
                          constraints: const BoxConstraints(),
                          visualDensity: VisualDensity.compact,
                        ),
                      ],
                    ),
                  ),
                  // 修改面板显示区域
                  AnimatedBuilder(
                    animation: _panelAnimation,
                    builder: (context, child) {
                      return ClipRect(
                        child: Align(
                          heightFactor: _panelAnimation.value,
                          child: child,
                        ),
                      );
                    },
                    child: keyboardHeight > 0
                        ? const SizedBox.shrink()
                        : _buildPanelContent(),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
} 